#include "cv.h"
#include "highgui.h"
#include <iostream>

using namespace std;

/* EXPERIMENTAL
Whatever is in the directory of the executable named "snap.jpg" will be used as the image.  The program displays streaming video until the user presses "esc".  The program will then take the last frame and use it as the template.  The program then compares the template to the image and, if found, will place a red rectangle around the matching image.

example in terminal:

./snap_temp

OR (if it worked, which it doesn't)

./snap_temp video.avi


Note: There is a flaw in OpenCV so the second command won't work
*/


int main( int argc, char** argv ) {

	//const char WINDOW_NAME = "SNAPSHOT TEMPLATE MATCH";
	IplImage	*res;
	CvPoint		minloc, maxloc;
	double		minval, maxval;
	int			img_width, img_height;
	int			tpl_width, tpl_height;
	int			res_width, res_height;

	cvNamedWindow( "SNAPSHOT TEMPLATE MATCH VIDEO", CV_WINDOW_AUTOSIZE );
	CvCapture* capture;
	if(argc == 1){
		capture = cvCreateCameraCapture(-1);	
	}
	else{
		capture = cvCreateFileCapture(argv[1]);
	}

	IplImage* tpl;
	IplImage* img = cvLoadImage("snap.jpg", CV_LOAD_IMAGE_COLOR );

	if( img == 0 ) {
		cout << "image not in directory of executable";
		return -1; 
	}
	/* get image properties -- only needs to be done once */
	img_width  = img->width;
	img_height = img->height;

	while(1) {
		tpl = cvQueryFrame( capture );
		cvShowImage("SNAPSHOT TEMPLATE MATCH VIDEO", tpl);
		/* get templates's properties of the current frame*/
		tpl_width  = tpl->width;
		tpl_height = tpl->height;
		res_width  = img_width - tpl_width + 1;
		res_height = img_height - tpl_height + 1;
		/* create new image for template matching computation */
		res = cvCreateImage( cvSize( res_width, res_height ), IPL_DEPTH_32F, 1 );
		/* choose template matching method to be used */
		cvMatchTemplate( img, tpl, res, CV_TM_SQDIFF );
		//cvMatchTemplate( img, tpl, res, CV_TM_SQDIFF_NORMED );
		//cvMatchTemplate( img, tpl, res, CV_TM_CCORR );
		//cvMatchTemplate( img, tpl, res, CV_TM_CCORR_NORMED );
		//cvMatchTemplate( img, tpl, res, CV_TM_CCOEFF );
		//cvMatchTemplate( img, tpl, res, CV_TM_CCOEFF_NORMED );

		cvMinMaxLoc( res, &minval, &maxval, &minloc, &maxloc, 0 );

		/* draw red rectangle */
		cvRectangle( tpl, 
				 cvPoint( minloc.x, minloc.y ), 
				 cvPoint( minloc.x + tpl_width, minloc.y + tpl_height ),
				 cvScalar( 0, 0, 255, 0 ), 1, 0, 0 );
		//finishes when escape is pressed
		char c = cvWaitKey(20);
		if (c == 27) break; //if esc (27 = esc in ASCII) is pressed, loop exits		
	}
	
	cvReleaseImage( &tpl );
	cvReleaseImage( &img );
	cvDestroyWindow("SNAPSHOT TEMPLATE MATCH VIDEO");
	cvReleaseCapture( &capture );
}
